import json
import socket
import traceback

from common.calculator_func import calculator
from common.register_center import register_all_method
from common.result_func import return_error
from utils import constant

if __name__ == '__main__':
    charset = 'utf-8'
    ip = '127.0.0.1'
    port = 15000
    s = socket.socket()
    s.bind((ip, port))
    s.listen(5)
    # 全部方法注入全局变量
    constant.public_func_dic_list = register_all_method()
    print('开启socket 监听')
    while True:
        cs, addr = s.accept()
        msg = cs.recv(65535).decode(charset)
        print('收到请求, 请求信息为:')
        print(msg)
        if msg.lower == 'exit':
            break
        elif msg.lower() == 'func_dic_list':
            cs.send(str(constant.public_func_dic_list).encode(charset))
            cs.close()
        else:
            try:
                msg = msg.replace("funcName", "func_name")
                result = calculator(msg)
            except ValueError:
                traceback.print_exc()
                result = return_error("请求错误, 请查看Python控制台", "")
            print('返回信息: ')
            result = json.dumps(result.__dict__)
            print(result)
            cs.send(result.encode(charset))
            cs.close()
